package com.web709.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.web709.common.R;
import com.web709.entity.ExchangeGoods;
import com.web709.entity.Product;
import com.web709.service.ExchangeGoodsService;
import com.web709.service.ProductService;
import com.web709.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/exchange")
@Api(tags = "商品兑换管理")
@Slf4j
public class ExchangeGoodsController {
    @Autowired
    private ExchangeGoodsService exchangeGoodsService;

    @Autowired
    private ProductService productService;

    @GetMapping("/page")
    @ApiOperation("分页查询兑换记录")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "page", value = "页码", defaultValue = "1", dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页数量", defaultValue = "10", dataType = "Integer"),
        @ApiImplicitParam(name = "userId", value = "用户ID（可选）", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "productId", value = "商品ID（可选）", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "token", paramType = "header", dataType = "String")
    })
    public R<Page<ExchangeGoods>> page(
        @RequestParam(defaultValue = "1") Integer page,
        @RequestParam(defaultValue = "10") Integer pageSize,
        @RequestParam(required = false) Integer userId,
        @RequestParam(required = false) Integer productId) {
        
        try {
            Page<ExchangeGoods> pageInfo = new Page<>(page, pageSize);
            LambdaQueryWrapper<ExchangeGoods> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加条件查询
            if (userId != null) {
                queryWrapper.eq(ExchangeGoods::getUserId, userId);
            }
            
            if (productId != null) {
                queryWrapper.eq(ExchangeGoods::getProductId, productId);
            }
            
            // 按创建时间降序排序
            queryWrapper.orderByDesc(ExchangeGoods::getCreateTime);
            
            exchangeGoodsService.page(pageInfo, queryWrapper);
            log.info("Successfully fetched exchange goods page {} with size {}", page, pageSize);
            return R.success(pageInfo);
        } catch (Exception e) {
            log.error("Error occurred while fetching exchange goods pages", e);
            return R.error("系统内部错误");
        }
    }
    
    @GetMapping("/{id}")
    @ApiOperation("根据ID查询兑换记录")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "兑换记录ID", required = true, dataType = "Integer"),
        @ApiImplicitParam(name = "token", paramType = "header", dataType = "String")
    })
    public R<ExchangeGoods> getById(@PathVariable Integer id) {
        try {
            ExchangeGoods exchangeGoods = exchangeGoodsService.getById(id);
            if (exchangeGoods != null) {
                return R.success(exchangeGoods);
            } else {
                return R.error("兑换记录不存在");
            }
        } catch (Exception e) {
            log.error("Error occurred while getting exchange goods by id: {}", id, e);
            return R.error("系统内部错误");
        }
    }
    
    @GetMapping("/user")
    @ApiOperation("获取当前用户的兑换记录")
    @ApiImplicitParam(name = "token", required = true, paramType = "header", dataType = "String")
    public R<Page<ExchangeGoods>> getCurrentUserExchanges(
            HttpServletRequest request,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        try {
            // 获取当前用户ID
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                return R.error("未提供token");
            }
            
            Claims claims = JwtUtils.parseJWT(token);
            Integer userId = (Integer) claims.get("userId");
            
            if (userId == null) {
                return R.error("无效的用户信息");
            }
            
            // 查询该用户的兑换记录
            Page<ExchangeGoods> pageInfo = new Page<>(page, pageSize);
            LambdaQueryWrapper<ExchangeGoods> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ExchangeGoods::getUserId, userId);
            queryWrapper.orderByDesc(ExchangeGoods::getCreateTime);
            
            exchangeGoodsService.page(pageInfo, queryWrapper);
            return R.success(pageInfo);
        } catch (Exception e) {
            log.error("Error occurred while getting current user exchanges", e);
            return R.error("系统内部错误");
        }
    }
    
    @PostMapping("/add")
    @ApiOperation("添加兑换记录")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "exchangeGoods", value = "兑换记录信息", required = true, dataType = "ExchangeGoods"),
        @ApiImplicitParam(name = "token", required = true, paramType = "header", dataType = "String")
    })
    public R<String> add(@RequestBody ExchangeGoods exchangeGoods, HttpServletRequest request) {
        try {
            // 设置创建时间
            exchangeGoods.setCreateTime(LocalDateTime.now());
            
            // 如果未设置状态，默认设置为正常
            if (exchangeGoods.getStatus() == '\0') {
                exchangeGoods.setStatus('1');
            }
            
            boolean saved = exchangeGoodsService.save(exchangeGoods);
            if (saved) {
                log.info("Exchange goods added successfully: {}", exchangeGoods.getId());
                return R.success("添加成功");
            } else {
                log.warn("Failed to add exchange goods");
                return R.error("添加失败");
            }
        } catch (Exception e) {
            log.error("Error occurred while adding exchange goods", e);
            return R.error("系统内部错误");
        }
    }
    
    @PutMapping("/update")
    @ApiOperation("更新兑换记录")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "exchangeGoods", value = "兑换记录信息", required = true, dataType = "ExchangeGoods"),
        @ApiImplicitParam(name = "token", required = true, paramType = "header", dataType = "String")
    })
    public R<String> update(@RequestBody ExchangeGoods exchangeGoods) {
        try {
            boolean updated = exchangeGoodsService.updateById(exchangeGoods);
            if (updated) {
                log.info("Exchange goods updated successfully: {}", exchangeGoods.getId());
                return R.success("更新成功");
            } else {
                log.warn("Failed to update exchange goods: {}", exchangeGoods.getId());
                return R.error("更新失败");
            }
        } catch (Exception e) {
            log.error("Error occurred while updating exchange goods", e);
            return R.error("系统内部错误");
        }
    }
    
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除兑换记录")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "兑换记录ID", required = true, dataType = "Integer"),
        @ApiImplicitParam(name = "token", required = true, paramType = "header", dataType = "String")
    })
    public R<String> delete(@PathVariable Integer id) {
        try {
            boolean removed = exchangeGoodsService.removeById(id);
            if (removed) {
                log.info("Exchange goods deleted successfully: {}", id);
                return R.success("删除成功");
            } else {
                log.warn("Failed to delete exchange goods: {}", id);
                return R.error("删除失败");
            }
        } catch (Exception e) {
            log.error("Error occurred while deleting exchange goods", e);
            return R.error("系统内部错误");
        }
    }
    
    @PutMapping("/updateStatus/{id}/{status}")
    @ApiOperation("更新兑换记录状态")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "兑换记录ID", required = true, dataType = "Integer"),
        @ApiImplicitParam(name = "status", value = "状态（1:正常, 0:取消, 2:已发货, 3:已完成）", required = true, dataType = "Character"),
        @ApiImplicitParam(name = "token", required = true, paramType = "header", dataType = "String")
    })
    public R<String> updateStatus(@PathVariable Integer id, @PathVariable Character status) {
        try {
            ExchangeGoods exchangeGoods = exchangeGoodsService.getById(id);
            if (exchangeGoods == null) {
                return R.error("兑换记录不存在");
            }
            
            exchangeGoods.setStatus(status);
            boolean updated = exchangeGoodsService.updateById(exchangeGoods);
            
            if (updated) {
                log.info("Exchange goods status updated successfully: {} to {}", id, status);
                return R.success("状态更新成功");
            } else {
                log.warn("Failed to update exchange goods status: {}", id);
                return R.error("状态更新失败");
            }
        } catch (Exception e) {
            log.error("Error occurred while updating exchange goods status", e);
            return R.error("系统内部错误");
        }
    }
}
